/**
 * 2019-05-11 23:25:19
 */
package com.cdxy.config.cors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Esion
 * （未使用）
 */
@Configuration
public class CorsFilter implements Filter {
    private static final transient Logger log = LoggerFactory.getLogger(CorsFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        servletResponse.setHeader("Access-Control-Allow-Origin", "*");
        servletResponse.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST,DELETE,PUT");
        servletResponse.setHeader("Access-Control-Max-Age", "3600");
        servletResponse.setHeader("X-Powered-By", " 3.2.1");
        servletResponse.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Length, X-Requested-With, Content-Type, Accept");
        servletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        // 判断是否为可选择性批量操作的请求，设置状态码返回
        String method = servletRequest.getMethod();
        if ("OPTIONS".equals(method)) {
            log.info("---------用户请求 options" + ((HttpServletRequest) request).getRequestURI());
            servletResponse.setStatus(HttpStatus.ACCEPTED.value());
            return;
        }
        log.info("---------用户请求" + ((HttpServletRequest) request).getRequestURI());
        chain.doFilter(request, response);
    }

}
